package com.tbit.uqbike.client.service.impl;

import com.tbit.uqbike.client.constant.RedisConstant;
import com.tbit.uqbike.client.dao.core.UserWxzffDao;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.pojo.UserWxzff;
import com.tbit.uqbike.client.service.RedisService;
import com.tbit.uqbike.client.service.UserWxzffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: chen
 * @Description:
 * @Date: 创建于 15:17 2022/3/24
 */
@Service
@Slf4j
public class UserWxzffServiceImpl implements UserWxzffService {

    @Autowired
    private UserWxzffDao userWxzffDao;

    @Autowired
    private RedisService redisService;

    @Override
    public UserWxzff getByUserId(Integer userId) {
        return userWxzffDao.getByUserId(userId);
    }

    @Override
    public List<UserWxzff> getByOpenId(String openId, Integer accountId) {
        Map<String, Object> map = new HashMap<>();
        map.put("openId", openId);
        map.put("accountId", accountId);
        return userWxzffDao.getByOpenId(map);
    }

    @Override
    public void add(UserWxzff userWxzff) {
        UserWxzff userWxzffDB = getByUserId(userWxzff.getUserId());
        if (userWxzffDB == null) {
            // 防重复提交
            if (redisService.setNx(RedisConstant.LOGIN_LOCK+userWxzff.getUserId(),userWxzff.getUserId().toString(),1)){
                if (userWxzff.getState() == null) {
                    userWxzff.setUpdateTime(new Date());
                    userWxzff.setState(0);
                }
                userWxzffDao.add(userWxzff);
            }
        } else {
            List<UserWxzff> userWxzffs = getByOpenId(userWxzff.getOpenId(), userWxzff.getAccountId());
            if (!userWxzffs.isEmpty()) {
                for (UserWxzff u : userWxzffs) {
                    //5.0.0 之前  userWxzff.getUpdateTime() 必定空指针
                    if (u.getUpdateTime().getTime() < userWxzff.getUpdateTime().getTime()) {
                        edit(userWxzff);
                    }
                }
            }
        }

    }

    @Override
    public void edit(UserWxzff userWxzff) {
        userWxzffDao.edit(userWxzff);
    }

    @Override
    public List<User> getUserByOpenId(String openId, Integer accountId) {
        Map<String, Object> map = new HashMap<>();
        map.put("openId", openId);
        map.put("accountId", accountId);
        return userWxzffDao.getUserByOpenId(map);
    }

    @Override
    public void del(Integer userId) {
        userWxzffDao.del(userId);
    }
}
